<route lang="json5">
  {
    style: {
      navigationStyle: 'custom',
      navigationBarTitleText: '择偶要求',
    },
  }
</route>
  
<template>
  <view class="bg-white" :class="[{ 'dark-color': themeConfig.theme === 'dark' }]">
    <wd-form ref="formRefs" :model="formData" :errorType="errorType">
      <!-- :custom-value-class="formData.ageFrom ? '' : 'cell-placeholder'" -->
      <wd-cell 
        title="年龄要求" 
        required 
        :value="formData.ageFrom ? `从${formData.ageFrom}岁到${formData.ageTo}岁` : '不限'"
        is-link 
        :to="toRangePicker('age')"
      ></wd-cell>
      <view class="border-1px"></view>
      
      <wd-cell 
        title="身高要求" 
        required 
        :value="formData.heightFrom ? `从${formData.heightFrom}cm到${formData.heightTo}cm` : '不限'"
        is-link 
        :to="toRangePicker('height')"
      ></wd-cell>
      <view class="border-1px"></view>
      
      <wd-cell 
        title="体重要求" 
        required 
        :value="formData.weightFrom ? `从${formData.weightFrom}kg到${formData.weightTo}kg` : '不限'"
        is-link 
        :to="toRangePicker('weight')"
      ></wd-cell>
      <view class="border-1px"></view>
      
      <!-- :custom-value-class="city ? '' : 'cell-placeholder'" -->
      <wd-cell 
        title="居住地" 
        :value="city ? city : '不限'" 
        is-link 
        :to="`/feature/areaPicker?cityName=不限&page=Require&isRequired=1&areaStr=${[formData.provinceId,formData.cityId,formData.districtId].filter(item => !!item).join(',')}`"
      ></wd-cell>
      <view class="border-1px"></view>
      
      <wd-cell 
        title="行业/职业" 
        :value="professionName ? professionName : '请选择'"
        :custom-value-class="professionName ? '' : 'cell-placeholder'"
        is-link 
        :to="'/feature/school?page=Require&type=profession&isNo=1&typeCode=' + formData.profession"
      ></wd-cell>
      <view class="border-1px"></view>

      <wd-picker 
        align-right 
        :columns="getIncome('matrimony')" 
        label="婚姻状况" 
        v-model="formData.maritalStatus" 
        prop="maritalStatus"
        :rules="[{ required: true, message: '请选择婚姻状况！' }]"
      />
      <view class="border-1px"></view>
      
      <wd-picker 
        align-right 
        :columns="getIncome('education')" 
        label="最低学历/文化层次" 
        v-model="formData.educationLevel" 
        prop="educationLevel"
        :rules="[{ required: true, message: '请选择最低学历/文化层次！' }]"
        label-width="280rpx"
      />
      <view class="border-1px"></view>
      
      <wd-picker 
        align-right 
        :columns="getIncome('income')" 
        label="年收入" 
        v-model="formData.incomeRange" 
        prop="incomeRange"
        :rules="[{ required: false, message: '请选择年收入情况！' }]"
      />
      <view class="border-1px"></view>
      
      <wd-picker 
        align-right 
        :columns="getIncome('assets')" 
        label="车房情况" 
        v-model="formData.housingCarStatus" 
        prop="housingCarStatus"
        :rules="[{ required: true, message: '请选择车房情况！' }]"
      />
      <view class="border-1px"></view>
    </wd-form>
    
    <!-- 保存择偶要求按钮 -->
    <view class="btn-full w-center pt-40rpx">
      <wd-button 
        class="btn-w-full btn-h-78"
        :loading="loading"
        @click="submit"
      >保存择偶要求</wd-button>
    </view>

    <view class="w-full h-78rpx"></view>
  </view>
</template>
  
<script lang="ts" setup>
import { UpdatePreferences } from '@/service/db_user';
import { useCommonStore, useThemeStore, useUserStore } from '@/store';
import { getCityName } from '@/utils';
import { useToast } from 'wot-design-uni';
import { deepClone } from 'wot-design-uni/components/common/util';

// 主题颜色
const { themeConfig } = useThemeStore();
const useCommon = useCommonStore();
const user = useUserStore();
const toast = useToast();

const formData = reactive({
  ageFrom: '',	// 理想年龄范围起始值	integer(int32)	
  ageTo: '',	// 理想年龄范围结束值	integer(int32)	
  heightFrom: '',	// 理想身高范围起始值（单位：cm）	number	
  heightTo: '',	// 理想身高范围结束值（单位：cm）	number	
  weightFrom: '',	// 理想体重范围起始值（单位：kg）	number	
  weightTo: '',	// 理想体重范围结束值（单位：kg）	number	
  provinceId: '',
  cityId: '',
  districtId: '',

  educationLevel: '',	// 理想学历（如：本科、硕士）	string	
  profession: '',	// 理想职业	string	
  incomeRange: '',	// 理想收入范围（如：5K-10K）	string	
  housingCarStatus: '',	// 理想车房情况（如：有房无车、车房都有）	string	
  maritalStatus: '',	// 理想婚姻状况（如：未婚、离异）	string	
})

const formRefs = ref();
const errorType = ref<"message" | "toast" | "none">('toast');
const submit = () => {
  // if (!formData.ageFrom) return toast.show('请选择年龄要求！');
  // if (!formData.heightFrom) return toast.show('请选择身高要求！');
  // if (!formData.weightFrom) return toast.show('请选择体重要求！');
  // if (!formData.provinceId) return toast.show('请选择居住所在地！');
  // if (!formData.profession) return toast.show('请选择行业/职业！');
  formRefs.value
    .validate()
    .then(({ valid }) => {
      if (!valid) return;
      
      user.loginSubmit = true;
      const data = {
        ...formData,
        userId: user.userInfo.id,
      }
      updatePreferences(data);
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}

const loading = ref(false);
// 择偶要求
const updatePreferences = async(data) => {
  try {
    loading.value = true;
    const res = await UpdatePreferences(data);
    loading.value = false;
    if (res.code != 200) {
      return toast.show(res.message);
    }
    toast.show('保存成功!');
    user.getUserInfo();
    user.getPreferencesQueryByUserId();

    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  } catch (error) {
    loading.value = false;
    console.log(error)
  }
}

const backfill = () => {
  if (!user.preferencesDetail.maritalStatus) return;
  for (const key in formData) {
    formData[key] = user.preferencesDetail[key];
  }

  professionName.value = getTypeName(user.preferencesDetail.profession);
  city.value = getCityName(user.preferencesDetail);
}

const getTypeName = (typeCode, name = 'profession') => {
  const list = useCommon.commonState.dictInfo[name] || [];
  const item = list.find(item => item.typeCode === typeCode) || { typeName: '' };
  return item.typeName || ''
}

const getIncome = computed(() => {
  return (name = 'income') => {
    const _dictInfo = useCommon.commonState.dictInfo || {};
    let list: any[] = deepClone(_dictInfo[name]) || [];
    list.unshift({
      id: name + '1839565474555',
      typeCode: 'none',
      typeName: '不限',
      label: '不限',
      value: 'none',
    })

    if (name === 'assets') {
      list = list.filter(item => item.label !== '保密');
    }
    return list;
  }
})

// 去选择年龄/身高/体重页面
const toRangePicker = (type = 'age') => {
  const dataList = [formData[`${type}From`], formData[`${type}To`]];
  const data = dataList.join(',');
  return '/feature/rangePicker?page=Require&type=' + type + '&data=' + data;
}

// 更新年龄/身高/体重
function handleUpdateData(data) {
  if (!data) return;
  const { type, dataList } = JSON.parse(data);
  if (dataList[0] == '0') {
    formData[`${type}From`] = null;
    formData[`${type}To`] = null;
    return
  }
  const [from, to] = dataList || []
  formData[`${type}From`] = from;
  formData[`${type}To`] = to;
}

const city = ref('');
// 更新城市
function handleUpdateArea(data) {
  if (!data) {
    city.value = '';
    Object.assign(formData, {
      provinceId: undefined, 
      cityId: undefined, 
      districtId: undefined
    })
    return
  }
  
  const [valStr, labelStr] = data.split('/');
  const [provinceVal, cityVal, districtVal] = valStr.split(',');
  const labelList = labelStr.split(',');
  
  // 如果地区名称重复, 只留一个
  if (labelList[0] === labelList[1]) {
    labelList.shift();
  }
  city.value = labelList.join('');
  Object.assign(formData, {
    provinceId: provinceVal, 
    cityId: cityVal, 
    districtId: districtVal
  })
}

const professionName = ref('');
// 更新学校/行业
function handleUpdateSchool(_data) {
  if (!_data) return;
  const { type, data } = JSON.parse(_data);
  formData[type] = data.typeCode || '';
  professionName.value = data.typeName || '';
}

onLoad((options) => {
  uni.$on('updateRangeRequire', handleUpdateData);
  uni.$on('updateAreaRequire', handleUpdateArea);
  uni.$on('updateSchoolRequire', handleUpdateSchool);
  
  user.getPreferencesQueryByUserId(() => {
    backfill();
  });
})

// 页面卸载时移除监听
onUnload(() => {
  uni.$off('updateRangeRequire', handleUpdateData);
  uni.$off('updateAreaRequire', handleUpdateArea);
  uni.$off('updateSchoolRequire', handleUpdateSchool);
})

onShow(() => {
  nextTick(() => {
    // 设置页面标题
    themeConfig.title = '择偶要求';
  })
  if (!user.userInfo.id) {
    uni.navigateTo({
      url: '/pages/login/index'
    })
    return
  }
})
</script>

<style lang="scss" scoped>
:root,
page {
  background-color: #fff !important;
}

.textarea-com {
  font-size: 28rpx !important;
  box-sizing: border-box !important;
}

:deep(.uni-textarea-textarea) {
  @extend .textarea-com;
}

:deep(.wot-theme-light) {
  .wd-textarea__inner,
  .uni-textarea-placeholder,
  .uni-textarea-wrapper {
    @extend .textarea-com;
    background-color: #FAF7FF !important;
  }

  .wd-textarea {
    background-color: #FAF7FF !important;
  }
}

:deep(.wot-theme-dark) {
  .wd-textarea,
  .uni-textarea-placeholder,
  .uni-textarea-wrapper {
    background-color: #141414 !important;
  }
}

:deep(.wd-input) {
  padding-right: 44rpx !important;
}

// 覆盖 wd-slider 样式 start
:deep(.wd-slider__label),
:deep(.wd-slider__label-min),
:deep(.wd-slider__label-max) {
  display: none
}
:deep(.wd-slider) {
  padding-top: 26rpx;

  .wd-slider__button {
    border: 3rpx solid #986DF0;
  }
}
// 覆盖 wd-slider 样式 end

:deep(.wd-cell__right) {
  flex: 2 !important;
}
:deep(.cell-placeholder) {
  color: #bfbfbf;
}
</style>
    